package com.demo.rabbitmq.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author sc
 * Created on  2018/9/16
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory cf = new ConnectionFactory();
        cf.setVirtualHost("/");
        cf.setHost("localhost");
        cf.setPort(5672);
        cf.setNetworkRecoveryInterval(3000);
        cf.setAutomaticRecoveryEnabled(true);

        Connection connection = cf.newConnection();
        Channel channel = connection.createChannel();
        String exchange = "test_direct_exchange";
        String exchangeType = "direct";
        String queueName = "test_direct_queue";
        String routingKey =  "test.direct";

        channel.exchangeDeclare(exchange,exchangeType);
        channel.queueDeclare(queueName,true,false,false,null);

        channel.queueBind(queueName,exchange,routingKey);

        QueueingConsumer qc = new QueueingConsumer(channel);

        channel.basicConsume(queueName, true,qc);

        while (true){
            QueueingConsumer.Delivery delivery = qc.nextDelivery();
            Object author = delivery.getProperties().getHeaders().get("author");
            System.out.println(author);
            System.out.println(new String(delivery.getBody()));
        }
    }
}
